/**
 * Created by wangxiaoqiang on 2017/9/18.
 */

let app = new Vue({

    el: "#update_goods",
    data: {
        resources: {
            categoryList: [],
            goodsDetail:[],
            freightTempList: [],
            attrClassList: [],
            attrList: [],
            mainImg:[],
            bannerImg:[],
            imgPath: fileServerPath,
        }
    },
    mounted: function () {
        this.getGoodsById();
        this.getAttrClassList();
        this.inpValidate();
    },
    methods: {
        //根据id获取单个商品
        getGoodsById:function () {
            let id = wxqUI.getUrlParam("id");
            $.get(rootPath+"/goods/"+id, (res)=> {
                if(res.meta.code === 200){
                    this.resources.goodsDetail = res.data;
                    this.resources.bannerImg = res.data.pic_banner?res.data.pic_banner.split(",") :'';
                    this.resources.mainImg = res.data.pic_main?res.data.pic_main.split(","):'';
                    let tempData = JSON.parse(res.data.goodsAttr_json);
                    for (let i = 0; i<tempData.length;i++){
                        for (let j = 0 ;j<tempData[i].goodsAttrList.length;j++ ){
                            this.resources.attrList.push(tempData[i].goodsAttrList[j])
                        }
                    }
                    this.getCategoryList();

                }else alert("查询出错--"+res.meta.code)
            })
        },

        //获取分类列表
        getCategoryList: function () {
            $.get(rootPath + "/category/all", (res) => {
                if (res.meta.code === 200) {
                    this.resources.categoryList = res.data;
                    //调用设置默认值方法，确保商品的数据已经获取到
                    this.setSelectDefault($("#cat_id"),this.resources.goodsDetail,this.resources.categoryList,"category")
                } else console.log(res.meta.code)
            })
        },

        //获取运费模板列表
       /* getFreightTempList: function () {
            $.get(rootPath + "/freight/all", (res) => {
                if (res.meta.code === 200) {
                    this.resources.freightTempList = res.data;
                    //调用设置默认值方法，确保商品的数据已经获取到
                    this.setSelectDefault($("#freight_id"),this.resources.goodsDetail,this.resources.freightTempList,"freight")
                } else console.log(res.meta.code)
            })
        },*/

        //获取规格属性类别列表
        getAttrClassList: function () {
            $.get(rootPath + "/goods/attr/class/all", (res) => {
                if (res.meta.code === 200) {
                    this.resources.attrClassList = res.data
                } else console.log(res.meta.code)
            })
        },

        /**
         * 设置下拉选项的默认选中值
         * @param node 添加option的select dom节点
         * @param goodsDetail 商品的数据，用于获取id
         * @param list 下拉选项的列表值，用于匹配商品中对应的id
         * @param name 相当于id对应的名字
         */
        setSelectDefault:function (node,goodsDetail,list,name) {
            let str = ``;
            for(let item in list){
                if(list[item].id === goodsDetail[name].id){
                    str += `<option selected value="${list[item].id}">${list[item].name}</option>`;
                }else {
                    str += `<option value="${list[item].id}">${list[item].name}</option>`;
                }
            }
            node.empty();
            node.append(str)
        },

        //上传规格图片，添加规格到临时列表
        addAttr: function () {
            let attr_data = new NiceValidate([
                {dom: document.getElementById("attr_class")},
                {dom: document.getElementById("attr_name")},
                {dom: document.getElementById("increase_price")},
                {dom: document.getElementById("attr_desc"),isNull:true},
                {dom: document.getElementById("attr_number"),isNull:true},
            ]).niceValidate();

            if (attr_data) {
                if(!attr_data.attr_number){
                    attr_data.attr_number = 0
                }
                //设置按钮不可点击
                setStatus.setDisable($("#attr_submit"));
                let files = document.querySelector("#attr_img").files;

                //上传数据
                uploadFile(files).then((res) => {
                    if(res.meta.code === 200){
                        attr_data.attr_img = res.data.length ? res.data[0].savePath : "";
                        for(let item in this.resources.attrClassList){
                            if(attr_data.attr_class == this.resources.attrClassList[item].id){
                                attr_data.attr_class_object = this.resources.attrClassList[item]
                            }
                        }
                        this.resources.attrList.push(attr_data);
                        setStatus.setEnable($("#attr_submit"), '<i class="fa fa-plus"></i>');//恢复按钮点击
                    }else alert("图片上传失败--"+res.meta.code)
                })
            }
        },

        //删除item
        deleteAttrItem: function (e) {
            let item_index = e.target.getAttribute("item_index");
            switch (e.target.getAttribute("img_type")) {
                case "main_img":
                    this.resources.mainImg.forEach((item, index) => {
                        if (index == item_index) {
                            this.resources.mainImg.splice(parseInt(item_index), 1);
                        }
                    });
                    break;
                case "banner_img":
                    this.resources.bannerImg.forEach((item, index) => {
                        if (index == item_index) {
                            this.resources.bannerImg.splice(parseInt(item_index), 1);
                        }
                    });
                    break;
                case "attr_img":
                    this.resources.attrList.forEach((item, index) => {
                        if (index == item_index) {
                            this.resources.attrList.splice(parseInt(item_index), 1);
                        }
                    });
                    break;
                default:
                    break
            }
        },

        //上传商品的展示主图
        uploadMainImg:function () {
            let files = document.querySelector("#pic_main").files;
            //上传数据
            uploadFile(files).then((res) => {
                if(res.meta.code === 200){
                    this.resources.mainImg = [];
                    for (let item in res.data){
                        this.resources.mainImg.push(res.data[item].savePath)
                    }
                }else alert("图片上传失败--"+res.meta.code);
            })
        },

        //上传商品banner图
        uploadBannerImg:function () {
            let files = document.querySelector("#pic_banner").files;
            //上传数据
            uploadFile(files).then((res) => {
                if(res.meta.code === 200){
                    this.resources.bannerImg = [];
                    for (let item in res.data){
                        this.resources.bannerImg.push(res.data[item].savePath)
                    }
                }else alert("图片上传失败--"+res.meta.code)
            })
        },

        //输入验证
        inpValidate:function () {
            return new NiceValidate([
                {dom: document.getElementById("goods_name")},
                {dom: document.getElementById("cat_id")},
                {dom: document.getElementById("goods_sn")},
                {dom: document.getElementById("goods_number")},
                /*{dom: document.getElementById("goods_weight")},*/
                {dom: document.getElementById("price")},
                {dom: document.getElementById("hot_sort"),range:[1,9],rangeErr:"数字在九位以内"},
                {dom: document.getElementById("member_price")},
                {dom: document.getElementById("goods_brief")},
                /*{dom: document.getElementById("goods_desc")},*/
                {dom: document.getElementById("seller_note"),isNull:true},
               /* {dom: document.getElementById("freight_id")},*/
            ])
        },
        //修改商品所有信息
        updateGoods:function () {
            let goods_data = this.inpValidate().niceValidate();
            if(goods_data){
                goods_data.goodsAttrs_json = JSON.stringify(this.resources.attrList);   //商品规格
                goods_data.pic_main = this.resources.mainImg.toString();           //主图
                goods_data.pic_banner = this.resources.bannerImg.toString();       //商品banner图
                goods_data.freight_id = 1; //默认1
                $.post(rootPath+"/goods/"+wxqUI.getUrlParam("id"),goods_data,function (res) {
                    if(res.meta.code === 200){
                        alert("修改成功")
                    }else alert("修改失败--"+res.meta.code)
                });
            }
        }
    }
});



